<template>
  <div class="home-page">
    <div class="banner">
      <div class="container">
        <h1 class="logo-font">conduit</h1>
        <p>A place to share your knowledge.</p>
      </div>
    </div>

    <div class="container page">
      <div class="row">
        <div class="col-md-9">
          <div class="feed-toggle">
            <ul class="nav nav-pills outline-active">
              <li class="nav-item" v-if="user">
                <nuxt-link
                  exact
                  class="nav-link"
                  :class="{ active: tab === 'your_feed' }"
                  @click.prevent="tabClick()"
                  :to="{
                    path: '/',
                    query: {
                      tab: 'your_feed',
                    },
                  }"
                >Your Feed</nuxt-link>
              </li>
              <li class="nav-item">
                <nuxt-link
                  exact
                  class="nav-link"
                  :class="{ active: tab === 'global_feed' }"
                  :to="{ path: '/', query: { tag: undefined, page: 1 } }"
                >Global Feed</nuxt-link>
              </li>
              <li class="nav-item" v-if="$route.query.tag">
                <a class="nav-link active" @click.prevent># {{ $route.query.tag }}</a>
              </li>
            </ul>
          </div>

          <!-- 文章列表组件 -->
          <article-item :articles="articles" />

          <!-- 分页列表 -->
          <page-item :pageCount="pageCount" />
        </div>

        <div class="col-md-3">
          <div class="sidebar">
            <p>Popular Tags</p>

            <div class="tag-list">
              <nuxt-link
                v-for="tag in tags"
                :to="{
                  path: '/',
                  query: {
                    tag: tag,
                    page: 1,
                    tab: undefined,
                  },
                }"
                class="tag-pill tag-default"
                :key="tag"
                @click.native="filterTag(tag)"
              >{{ tag }}</nuxt-link>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getArticles, getTags, getFeedArticles } from "../../api/home";
import { mapState } from "vuex";
import ArticleItem from "@/components/article-item";
import PageItem from "@/components/page-item";

export default {
  name: "home",
  watchQuery: ["page", "tag", "tab"],
  components: {
    ArticleItem,
    PageItem
  },
  data() {
    return {
      tabs: [
        {
          label: "Your Feed",
          show: true,
          tag: "feed",
          active: false
        },
        {
          label: "Global Feed",
          show: true,
          active: true,
          tag: undefined
        }
      ],
      offset: 0
    };
  },
  async asyncData({ query, store }) {
    const limit = 20;
    const page = Number.parseInt(query.page || 1);
    const getArticlesFn =
      query.tab === "your_feed" && store.state.user
        ? getFeedArticles
        : getArticles;
    let [tagRes, listRes] = await Promise.all([
      getTags(),
      getArticlesFn({
        offset: limit * (page - 1),
        tag: query.tag
      })
    ]);
    listRes.data.articles.forEach(x => (x.favoriteDisabled = false));
    return {
      tags: tagRes.data.tags,
      articles: listRes.data.articles,
      articlesCount: listRes.data.articlesCount,
      tab: query.tab || query.tag || "global_feed",
      limit,
      page
    };
  },
  computed: {
    ...mapState(["user"]),
    pageCount() {
      return Math.ceil(this.articlesCount / this.limit);
    }
  },
  methods: {
    async updateArticles(params) {
      this.articles = [];
      let listRes =
        params.tag === "feed"
          ? await getFeedArticles()
          : await getArticles(params);
      this.articles = listRes.data.articles;
      this.articlesCount = listRes.data.articlesCount;
    },
    filterTag(tag) {
      this.offset = 0;
      this.tabs.forEach(item => (item.active = false));
      this.tabs.splice(2, 1, {
        label: "#" + tag,
        show: true,
        tag: tag,
        active: true
      });
    },
    tabClick(tab) {
      this.offset = 0;
      if (!tab.label.startsWith("#")) {
        this.tabs.splice(2, 1);
      } else return;
      if (tab.tag === "feed") {
        this.tabs[0].active = true;
        this.updateArticles(tab);
      } else {
        this.tabs[1].active = true;
        this.$router.push({
          path: "/",
          query: {
            tag: undefined,
            page: 1
          }
        });
      }
    }
  }
};
</script>

<style>
</style>